import java.util.PriorityQueue;

public class MyTimeTask implements Comparable<MyTimeTask> {

    public Runnable runnable;
    //此处时间最后转换成ms级别的时间戳
    public long time;

    public MyTimeTask(Runnable runnable, long time) {
        this.runnable = runnable;
        //换算时间
        this.time = System.currentTimeMillis() + time;
    }

    void run() {
        runnable.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimeTask o) {
        return (int) (o.time - this.time);
    }
}

class MyTimer {
    //存储任务优先级队列
    private PriorityQueue<MyTimeTask> queue = new PriorityQueue<>();
    //定义锁对象
    Object locker = new Object();
    public MyTimer() {
        Thread t = new Thread(() -> {
            try {
                while (true) {
                    synchronized (locker) {
                        if (queue.size() == 0) {
                            locker.wait();
                        }
                    }
                    MyTimeTask task = queue.peek();
                    long curTime = System.currentTimeMillis();
                    //时间到了
                    if (curTime >= task.getTime()) {
                        task.run();
                        queue.poll();
                    } else {
                        //时间没到,继续等待
                        locker.wait(task.getTime() - curTime);
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
    }

    public void MySchedult(Runnable runnable, long time) {
        MyTimeTask tast = new MyTimeTask(runnable, time);
        queue.offer(tast);
        locker.notify();
    }
}
